package com.s10.ecloud.web.util;

import java.util.Date;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import com.s10.ecloud.web.model.User;

public class EmailUtils {

	public static ResourceBundle bundle = ResourceBundle.getBundle("mail");

	/**
	 * 注册成功后,向用户发送帐户激活链接的邮件
	 * 
	 * @param user
	 *            未激活的用户
	 */
	public static void sendAccountActivateEmail(User user) {

		Session session = getSession();
		MimeMessage message = new MimeMessage(session);
		try {
			message.setSubject("帐户激活邮件");
			message.setSentDate(new Date());
			message.setFrom(new InternetAddress(bundle.getString("from")));
			message.setRecipient(RecipientType.TO,
					new InternetAddress(user.getEmail()));
			message.setContent(
					"<a href='" + GenerateLinkUtils.generateActivateLink(user)
							+ "'>点击激活帐户</a>", "text/html;charset=utf-8");
			// 发送邮件
			Transport.send(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发送重设密码链接的邮件
	 */
	public static void sendResetPasswordEmail(User user) {
		Session session = getSession();
		MimeMessage message = new MimeMessage(session);
		try {
			message.setSubject("找回您的帐户与密码");
			message.setSentDate(new Date());
			message.setFrom(new InternetAddress(bundle.getString("from")));
			message.setRecipient(RecipientType.TO,
					new InternetAddress(user.getEmail()));
			message.setContent("要使用新的密码, 请使用以下链接启用密码:<br/><a href='"
					+ GenerateLinkUtils.generateResetPwdLink(user)
					+ "'>点击重新设置密码</a>", "text/html;charset=utf-8");
			// 发送邮件
			Transport.send(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Session getSession() {
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol",
				bundle.getString("protocol"));
		props.setProperty("mail.smtp.host", bundle.getString("host"));
		props.setProperty("mail.smtp.port", bundle.getString("port"));
		props.setProperty("mail.smtp.auth", bundle.getString("auth"));

		Session session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				String password = null;
				// InputStream is =
				// EmailUtils.class.getResourceAsStream("password.dat");
				// byte[] b = new byte[1024];
				// try {
				// int len = is.read(b);
				// password = bundle.getString("password");
				// } catch (IOException e) {
				// e.printStackTrace();
				// }
				return new PasswordAuthentication(bundle.getString("from"),
						bundle.getString("password"));
			}

		});
		return session;
	}
}
